package com.ruoyi.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.controller.common.CommonController;
import com.ruoyi.workstation.domain.User;
import com.ruoyi.workstation.domain.model.LoginBody;
import com.ruoyi.workstation.domain.model.UpdatePassword;
import com.ruoyi.workstation.service.IUserService;
import com.ruoyi.workstation.service.impl.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.UUID;

/**
 * 工作站，PC用户Controller
 *
 * @author ruoyi
 * @date 2024-01-12
 */
@Controller
@RequestMapping("/api/user")
public class ApiUserController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private IUserService userService;
    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     *
     * @param loginBody
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        User user = new User();
        user.setUsername(loginBody.getUsername());
        user.setPassword(loginBody.getPassword());
        List<User> list = userService.selectUserList(user);
        if (list == null || list.isEmpty()) {
            // 500 用户不存在
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }
        user = list.get(0);
        String token = tokenService.createToken(user);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        return AjaxResult.success("", map);
    }

    /**
     * 创建用户
     */
    @Log(title = "工作站，PC用户", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    @ResponseBody
    public AjaxResult create(HttpServletRequest request, @RequestBody User user) {
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {
            String uuid = UUID.randomUUID().toString();
            user.setUsername(uuid);
            user.setPassword("123456");

            user.setCreator(userId);
            user.setLastModifiedBy(userId);
            user.setUpdateTime(DateUtils.getNowDate());
            int rs = userService.insertUser(user);
            List<User> users = userService.selectUserList(user);
            user = users.get(0);
            user.setUsername("my" + (25648522 + user.getUserId()));
            userService.updateUser(user);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(JSON.toJSONString(user), e);
            if (e instanceof SQLIntegrityConstraintViolationException) {
                return new AjaxResult(AjaxResult.Type.USER_EXIST, "");
            } else {
                return AjaxResult.error();
            }
        }
    }


    /**
     * 修改用户
     */
    @Log(title = "工作站，修改用户", businessType = BusinessType.INSERT)
    @PutMapping("/update")
    @ResponseBody
    public AjaxResult update(HttpServletRequest request, @RequestBody User user) {
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {
            user1.setName(user.getName());
            user1.setSex(user.getSex());
            user1.setBirthday(user.getBirthday());
            user1.setMobile(user.getMobile());
            user1.setOrgName(user.getOrgName());
            user1.setProvince(user.getProvince());
            user1.setCity(user.getCity());
            user1.setCounty(user.getCounty());
            user1.setAddress(user.getAddress());
            user1.setJob(user.getJob());

            user1.setLastModifiedBy(userId);
            user1.setUpdateTime(DateUtils.getNowDate());
            userService.updateUser(user1);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(JSON.toJSONString(user), e);
            if (e instanceof SQLIntegrityConstraintViolationException) {
                return new AjaxResult(AjaxResult.Type.USER_EXIST, "");
            } else {
                return AjaxResult.error();
            }
        }
    }

    /**
     * 工作站管理员，重置普通用户密码
     */
    @Log(title = "工作站管理员，重置普通用户密码", businessType = BusinessType.INSERT)
    @PutMapping("/reset/password/{userId}")
    @ResponseBody
    public AjaxResult resetPassword(HttpServletRequest request, @PathVariable("userId") Long uId) {
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {
            User user = userService.selectUserByUserId(uId);
            if (user1 == null) {
                return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
            }
            user.setPassword("123456");
            user.setLastModifiedBy(userId);
            user.setUpdateTime(DateUtils.getNowDate());

            userService.updateUser(user);
            return AjaxResult.success();
        } catch (Exception e) {
            log.error(uId + "", e);
            return AjaxResult.error();
        }
    }

    /**
     * 用户修改密码
     */
    @Log(title = "用户修改密码", businessType = BusinessType.INSERT)
    @PutMapping("/update/password")
    @ResponseBody
    public AjaxResult resetPassword(HttpServletRequest request, @RequestBody UpdatePassword updatePassword) {
        if (updatePassword.getNewPassword() == null || updatePassword.getNewPassword().length() == 0) {
            return new AjaxResult(AjaxResult.Type.USER_PASSWORD_IS_NULL_ERROR, "");
        }
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {

            if (user1 == null) {
                return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
            }

            if (user1.getPassword().equals(updatePassword.getOldPassword())) {
                user1.setPassword(updatePassword.getNewPassword());
                user1.setLastModifiedBy(userId);
                user1.setUpdateTime(DateUtils.getNowDate());
                userService.updateUser(user1);
                return AjaxResult.success();
            } else {
                return new AjaxResult(AjaxResult.Type.USER_PASSWORD_ERROR, "");
            }
        } catch (Exception e) {
            log.error(JSONObject.toJSONString(updatePassword), e);
            return AjaxResult.error();
        }
    }


    /**
     * 获取用户
     */
    @Log(title = "获取用户", businessType = BusinessType.INSERT)
    @GetMapping("/list")
    @ResponseBody
    public AjaxResult list(HttpServletRequest request) {
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        try {
            User user = new User();
            user.setCreator(userId);
            List<User> list = userService.selectUserList(user);
            list.stream().parallel().forEach(user2 -> {
                user2.setPassword("");
            });
            return AjaxResult.success(list);
        } catch (Exception e) {
            if (e instanceof SQLIntegrityConstraintViolationException) {
                return new AjaxResult(AjaxResult.Type.USER_EXIST, "");
            } else {
                return AjaxResult.error();
            }
        }
    }

    /**
     * 获取用户
     */
    @Log(title = "获取用户", businessType = BusinessType.OTHER)
    @GetMapping("/get")
    @ResponseBody
    public AjaxResult get(HttpServletRequest request) {
        Long userId = tokenService.getLoginUserId(request);
        User user1 = userService.selectUserByUserId(userId);
        if (user1 == null) {
            return new AjaxResult(AjaxResult.Type.USER_NOT_EXIST, "");
        }

        return AjaxResult.success(user1);
    }
}
